<template>
	<view class="page">
		<div v-for="commodity in commodityList" :key="commodity.id" class="main-box">
			<u-row gutter="0">
				<u-col span="5">
					<image :src="commodity.image1" alt="product image" mode="aspectFit"
						style="margin-left:10px; width: 230rpx; height: 300rpx;" />
				</u-col>
				<u-col span="10">
					<div>
						<h3>{{ commodity.name }}</h3>
					</div>
					<div>{{ truncateDescription(commodity.describe) }}</div>
					<div class="price">{{ commodity.price }} {{ commodity.unitPrice }}</div>
					<button @click="getById(commodity.id)">查看详情</button>
				</u-col>
			</u-row>
		</div>

		<uni-pagination :current="commodityPageQuery.page" :total="60" @change="handlePage" />
	</view>
</template>

<script>
	export default {
		data() {
			return {
				token: null,
				//商品列表
				commodityList: [],
				//分页请求的参数
				commodityPageQuery: {
					name: "",
					page: 1,
					pagesize: 10,
				}
			}
		},
		created() {
			//获取token在vue变量中
			this.recordToken();
			this.pagingToQueryAllCommodity();

		},
		methods: {
			/**
			 * 截取商品描述字符串，并添加省略号
			 */
			truncateDescription(description) {
				if (description.length > 10) {
					return description.slice(0, 10) + '...';
				} else {
					return description;
				}
			},

			/**
			 * 分页点击事件
			 */
			handlePage(params) {
				this.commodityPageQuery.page = params.current;
				this.pagingToQueryAllCommodity();
			},

			/**
			 * 商品分页查询
			 */
			pagingToQueryAllCommodity() {
				const url = "http://localhost:8088/buyer-commodity/paginationQuery?name=" +
					this.commodityPageQuery.name + "&page=" +
					this.commodityPageQuery.page + "&pageSize=" +
					this.commodityPageQuery.pagesize;
				console.log(url);
				uni.request({
					url: url,
					method: 'GET',
					header: {
						'content-type': 'application/json',
						'token': this.token
					},
					success: (res) => {
						this.commodityList = res.data.data.records;
						console.log(this.commodityList.records);
					},
					fail: (err) => {
						console.error('获取商品分页失败：', err);
					}
				});
			},

			/**
			 * 根据id查询商品信息
			 */
			getById(id) {
				const url = "/pages/productDetails/productDetails?id=" + id;
				uni.navigateTo({
					url: url,
					animationType: 'pop-in',
					animationDuration: 300
				})
			},

			recordToken() {
				this.token = localStorage.getItem('token');
				console.log(this.token);
			},
		}
	}
</script>


<style lang="scss">
	.main-box {
		background-color: #fff;
		margin-bottom: 10rpx;
		// margin-top: 10rpx;
		margin-left: 5rpx;
		margin-right: 5rpx;
		border-radius: 10px;
	}

	.price {
		color: red;
	}

	.page {
		background-color: #EEEDEB;
		/* 设置页面背景颜色 */
	}
</style>